<script setup lang="ts">
import { getConsultOrderPre, createConsultOrder, getConsultOrderPayUrl } from '@/services/consult'
import { getPatientDetail } from '@/services/user'
import { useConsultStore } from '@/stores/index'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showLoadingToast, showToast } from 'vant'
import { onMounted } from 'vue'
import { ref } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { useRouter } from 'vue-router'

// 获取预支付信息
const consultStore = useConsultStore()
const payInfo = ref({} as ConsultOrderPreData)
const getPayInfo = async () => {
  const res = await getConsultOrderPre({
    type: consultStore.consult.type,
    illnessType: consultStore.consult.illnessType
  })
  payInfo.value = res.data
  // 存储优惠券信息
  consultStore.setCoupon(res.data.couponId)
}
// 获取患者信息
const patient = ref({} as Patient)
const getPatient = async () => {
  const res = await getPatientDetail(consultStore.consult.patientId as string)
  patient.value = res.data
}

onMounted(() => {
  // 页面初始化时，发现问诊记录不在了
  if (!consultStore.consult.type) {
    showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付'
    }).then(() => {
      router.push('/')
    })
    return
  }
  getPayInfo()
  getPatient()
})

// 生成订单
const agree = ref(false)
const orderId = ref('')
const loading = ref(false)
const show = ref(false)
const paymentMethod = ref<0 | 1>()
// 点击立即支付
const createOrder = async () => {
  if (!agree.value) return showToast('请勾选我已同意')
  // 开启按钮 loading
  loading.value = true
  try {
    // 调用生成订单接口
    const res = await createConsultOrder(consultStore.consult)
    orderId.value = res.data.id
    // 清空问诊记录所有的数据
    consultStore.clear()
    // 打开选择支付方式的抽屉
    show.value = true
  } finally {
    // 关闭按钮 loading
    loading.value = false
  }
}
// 点击选择支付方式中的立即支付
const router = useRouter()
const pay = async () => {
  if (paymentMethod.value === undefined) return showToast('请选择支付方式')
  // loading 加载效果
  showLoadingToast('跳转支付')
  // 调用支付接口
  const res = await getConsultOrderPayUrl({
    paymentMethod: paymentMethod.value,
    orderId: orderId.value,
    payCallback: 'http://localhost:5173/room'
  })
  // 跳转到支付宝页面
  window.location.href = res.data.payUrl
}

// 抽屉关闭前的回调函数，可以在该回调函数中控制抽屉是否关闭
const beforeClose = async () => {
  try {
    await showConfirmDialog({
      title: '关闭支付',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭',
      confirmButtonText: '继续支付'
    })
    // 点击继续支付（确定），不关闭抽屉
    return false
  } catch (error) {
    // 点击仍要关闭（取消）
    // 清空订单ID
    orderId.value = ''
    // 跳转到问诊订单列表页面
    router.push('/user/consult')
    // 关闭抽屉
    return true
  }
}
// 如果已经生成订单了，点击返回，不可回退
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 预支付信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient.name}| ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="consultStore.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 底部操作栏 -->
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="createOrder"
      :loading="loading"
    />
  </div>
  <van-action-sheet
    :before-close="beforeClose"
    v-model:show="show"
    title="选择支付方式"
    :closeable="false"
    :close-on-popstate="false"
  >
    <div class="pay-type">
      <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
      <van-cell-group>
        <van-cell title="微信支付" @click="paymentMethod = 0">
          <template #icon><cp-icon name="consult-wechat" /></template>
          <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
        </van-cell>
        <van-cell title="支付宝支付" @click="paymentMethod = 1">
          <template #icon><cp-icon name="consult-alipay" /></template>
          <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button type="primary" round block @click="pay">立即支付</van-button>
      </div>
    </div>
  </van-action-sheet>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
